package com.ah.hf.controller;

import com.ah.hf.common.BaseContext;
import com.ah.hf.common.R;
import com.ah.hf.entity.ShoppingCart;
import com.ah.hf.service.ShoppingCartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.omg.CORBA.BAD_CONTEXT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

//购物车
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    //添加购物车,菜品或者套餐加入到购物车
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        //设置用户id
        Long userId = BaseContext.getUserId();
        shoppingCart.setUserId(userId);

        //获取菜品id，判断是否为空
        Long dishId = shoppingCart.getDishId();

        //
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        if (dishId != null){
            //如果该不等于空，说明前端穿过来的是菜品id
            qw.eq(ShoppingCart::getDishId,dishId);
        }else{
            //套餐id
            qw.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //查询
        ShoppingCart shoppingCart1 = shoppingCartService.getOne(qw);
        if (shoppingCart1 != null){
            Integer number = shoppingCart1.getNumber();
            shoppingCart1.setNumber(number+1);
            shoppingCartService.updateById(shoppingCart1);
        }else{
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            shoppingCart1 = shoppingCart;
        }

        return R.success(shoppingCart1);
    }

    @GetMapping("/list")
    public R<List<ShoppingCart>> query(){
        //获取userId
        Long userId = BaseContext.getUserId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();

        //查询条件
        qw.eq(ShoppingCart::getUserId,userId);
        qw.orderByAsc(ShoppingCart::getCreateTime);

        //获取ShoppingCart集合
        List<ShoppingCart> list = shoppingCartService.list(qw);
        return R.success(list);
    }
    //清空购物车
    @DeleteMapping("/clean")
    public R<String> clean(){
        Long userId = BaseContext.getUserId();
        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(qw);
        return R.success("清空购物车成功");
    }
}
